<template>
	<div style="padding-top: 5px">
		<el-tooltip class="box-item" effect="dark" content="美化sql" placement="top-end">
			<el-button text @click="formatSql()"><img src="@/assets/format.png" /></el-button>
		</el-tooltip>
		<el-tooltip class="box-item" effect="dark" content="执行" placement="top-end">
			<el-button :loading="executeSqlButton" @click="executeSql()" text><img src="@/assets/run.png" /></el-button>
		</el-tooltip>
	</div>
	<div style="height: calc(100vh - 650px); padding-top: 5px">
		<SqlStudio ref="sqlStudioRef" id="dataTableSqlConsoleId" heightAll></SqlStudio>
	</div>
	<el-tabs class="data-table-tabs">
		<el-tab-pane>
			<template #label>
				<span>
					<el-icon><DataLine /></el-icon>&nbsp;
					<span>执行结果</span>
				</span>
			</template>
			<div style="margin-top: 8px">
				<el-tag>tips：若记录超过100条，只显示前100条记录</el-tag>
			</div>
			<div v-loading="sqlResultLoading" style="height: 320px">
				<console-result ref="consoleResultRef"></console-result>
			</div>
		</el-tab-pane>
	</el-tabs>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import SqlStudio from './sql-studio.vue'
import ConsoleResult from '../../data-integrate/production/console-result.vue'
import { getMasterModelSqlExecuteApi, getMasterModelLogClearApi } from '@/api/data-governance/masterModel'
const sqlStudioRef = ref()
const consoleResultRef = ref()
const sqlResultLoading = ref(false)
const executeSqlButton = ref(false)

const props = defineProps({
	data: {
		type: Object,
		default: () => {
			return {}
		}
	},
	dataId: {
		type: String,
		default: ''
	}
})

const clearSqlValue = () => {
	if (sqlStudioRef.value) {
		sqlStudioRef.value.setEditorValue('')
	}

	if (consoleResultRef.value) {
		consoleResultRef.value.clear()
	}
}

//美化sql
const formatSql = () => {
	sqlStudioRef.value!.handleFormat()
}

// sql控制台
const executeSql = () => {
	// console.log(props.data)
	sqlResultLoading.value = true
	executeSqlButton.value = true
	const sqlDataForm = {}
	sqlDataForm.dataLayerId = props.data.projectId
	sqlDataForm.maxRowNum = 100
	sqlDataForm.statement = sqlStudioRef.value.getEditorValue()
	if (!sqlDataForm.statement) {
		ElMessage.warning('请输入sql！')
		sqlResultLoading.value = false
		executeSqlButton.value = false
		return
	}
	getMasterModelSqlExecuteApi(sqlDataForm).then(res => {
		const data = res.data
		if (!data.success) {
			ElMessage.error('执行失败，请查看日志信息排查原因！')
			consoleResultRef.value.init(data.result, 1)
		} else {
			ElMessage.success('执行成功')
			consoleResultRef.value.init(data.result, 1)
		}
		sqlResultLoading.value = false
		executeSqlButton.value = false
		//清空后台产生的日志
		getMasterModelLogClearApi()
	})
}

defineExpose({
	clearSqlValue
})
</script>
<style lang="less" scoped></style>
